<?php

class AuthController extends Controller
{
    private $_identity;

    public function actionLogin()
    {
        $email = $_POST['email'];
        $password = $_POST['password'];

        if ($this->_identity === null) {
            $this->_identity = new UserIdentity($email, $password);
            $this->_identity->authenticate();
        }
        if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
            if (isset($_POST['rememberMe'])) {
                $rememberMe = $_POST['rememberMe'];
                $duration = $rememberMe ? 3600 * 24 * 30 : 0; // 30 days
                Yii::app()->user->login($this->_identity, $duration);
            } else {
                Yii::app()->user->login($this->_identity);
            }
            Yii::app()->session['_logged_email'] = $email;
        }
        if (isset($_POST['_ajax']) && $_POST['_ajax'] === 'true') {
            echo '{success:true}';
            Yii::app()->end();
        } else {
            if (isset($_POST['admin'])) {
                $this->redirect('index.php?r=admin/index');
            } else {
                $this->redirect('index.php');
            }
        }
    }

    public function actionLogout()
    {
        Yii::app()->user->logout();
        $this->redirect('index.php');
    }

    public function actionForgot()
    {
        $email = $_POST['email'];

        $person = Person::model()->findAll(array(
            'condition' => 'email = :email',
            'params' => array(':email' => $email)
        ));

        $newPassword = substr($person->firstname, 3) . 'P12';
        $params = array('firstName' => $person->firstname,
            'newPassword' => $newPassword);
        if ($person != null) {
            $this->sendMail('forgot_password', 'Forgot your password', $email, $params);
        }
    }
}